﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using System.Text;
using CardLogistics.Model.CardMaking;
using CardLogistics.DAL.CardMaking;

namespace CardLogistics.Web.MainPage.CardMaking.CardOutStorage
{
    public partial class AddEdit : BasePage
    {
        #region 变量
        #endregion
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardOutStorageData DAL = new DAL.CardMaking.CardMaking_CardOutStorageData();
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardOutStrgeDetailData DetailedDAL = new DAL.CardMaking.CardMaking_CardOutStrgeDetailData();
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardSeparateDetailData SepdtlDAL = new DAL.CardMaking.CardMaking_CardSeparateDetailData();
        string FileValue = ""; //白卡出库明细字段

        //private string separateId = ""; //离盒单Id

        /// <summary>
        /// 盒号集合
        /// </summary>
        protected Dictionary<string, string> CardNOList = null;
        /// <summary>
        /// 箱号号集合
        /// </summary>
        protected string BoxNOList = "";

        protected Dictionary<string, string> CardNOList_D = null;

        protected static DataTable DtAll = null;//系统中有效卡的 盒号、卡类型、供应商信息
        public static string TitleName
        {
            get;
            set;
        }
        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            CardNOList = new Dictionary<string, string>();
            CardNOList_D = new Dictionary<string, string>();
            BoxNOList = "";
            if (!IsPostBack)
            {
                OUTSTORAGEDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//出库日期
                STOCKCONTROLLER.Value = LoggedUser.USERFULLNAME;//库管员默认为当前登录用户
                InitControl(sender, e);

            }
        }
        #endregion


        #region 根据供应商和卡类型查询入库箱号
        private void BindSupp()
        {
            ddlSUPPID.Items.Clear();
            ListItem lt = new ListItem("---请选择---", "0");
            ddlSUPPID.Items.Add(lt);
            if (DtAll != null && DtAll.Rows.Count > 0)
            {
                foreach (DataRow dr in DtAll.Rows)
                {
                    ListItem tmpLt = new ListItem(dr["suppliersname"].ToString(), dr["suppid"].ToString());
                    if (!ddlSUPPID.Items.Contains(tmpLt))
                        ddlSUPPID.Items.Add(tmpLt);
                }
            }
            ddlSUPPID.SelectedValue = "0";
        }
        /// <summary>
        /// 供应商选择改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlSUPPID_selectChange(object sender, EventArgs e)
        {
            //根据供应商绑定卡类型数据
            BindCardTypeBySuppId();
        }
        /// <summary>
        /// 根据供应商绑定卡类型数据
        /// </summary>
        private void BindCardTypeBySuppId()
        {
            //ddlCardTypeId.Items.Clear();//清空卡片类型
            //ListItem lt = new ListItem("---请选择---", "0");
            // ddlCardTypeId.Items.Add(lt);
            //if (DtAll != null && DtAll.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in DtAll.Rows)
            //    {
            //        ListItem tmpLt = new ListItem(dr["Cardtypename"].ToString(), dr["Cardtypeid"].ToString());
            //        if (!ddlCardTypeId.Items.Contains(tmpLt))
            //            ddlCardTypeId.Items.Add(tmpLt);
            //    }
            //}
            //ddlCardTypeId.SelectedValue = "0";
            GetBoxList();
        }
        /// <summary>
        /// 卡类型选择改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlCardTypeId_selectChange(object sender, EventArgs e)
        {
            //if (ddlCardTypeId.SelectedValue != "0")
            //{
            //    //根据供应商和卡类型查询入库箱号
            //    GetBoxList();
            //}
        }

        //根据供应商和卡类型查询入库箱号
        private void GetBoxList()
        {
            string suppid = ddlSUPPID.SelectedValue;
            string cardtypeid = hf_CardType.Value;
            CardNOList = new Dictionary<string, string>();
            CardNOList_D = new Dictionary<string, string>();
            BoxNOList = "";
            //DtAll.DefaultView.Sort = "CardNo ASC";//按盒号排序
            DataView dv = DtAll.DefaultView;
            dv.Sort = "CardNo ASC";//按盒号排序
            DtAll = dv.ToTable();
            rkId.Value = DtAll.Rows[0]["CheckId"].ToString();//获取入库Id
            DataRow[] dr = DtAll.Select(" suppid='" + suppid + "' and Cardtypeid='" + cardtypeid + "' ");

            foreach (DataRow d in dr)
            {
                if (!CardNOList.Keys.Contains(d["cardno"].ToString()))
                    CardNOList.Add(d["startno"].ToString() + "|" + d["endno"].ToString() + "|" + d["boxno"].ToString() + "|" + d["CheckId"].ToString(), d["cardno"].ToString());
                if (!BoxNOList.Split(',').Contains(d["boxno"].ToString()))
                {
                    BoxNOList += d["boxno"].ToString() + ",";
                    //BoxNOList.Add(GetCardNOListByBox(d["boxno"].ToString(), dv), d["boxno"].ToString());
                    CardNOList_D.Add(GetCardNOListByBox(d["boxno"].ToString(), dv), d["boxno"].ToString());
                }
            }
            BoxNOList = "'" + BoxNOList.TrimEnd(',') + "'";
        }
        private string GetCardNOListByBox(string box, DataView dvAll)
        {
            string cardNoStr = "";
            for (int i = 0; i < dvAll.Count; i++)
            {
                if (dvAll[i]["boxno"].ToString() == box)
                    cardNoStr += dvAll[i]["cardno"].ToString() + "|";
            }
            //if (cardNoStr == "")
            //    return System.Guid.NewGuid().ToString();
            return cardNoStr.TrimEnd('|');
        }

        #endregion

        #region 得到一个对象实体
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public void InitControl(object sender, EventArgs e)
        {
            TitleName = GetStatusInfo(0, "白卡出库");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardMaking_CardOutStorage sData = DAL.GetModel(_key);
                    SetWebControls(this.Page, sData);
                    hf_DemandId.Value = sData.DEMANDID;//需求单ID
                    //根据白卡出库单查询出库明细
                    DataTable dt = DetailedDAL.GetInfoByCheckId(_key);
                    //dt.DefaultView.Sort = "StartNo ASC,EndNo ASC";
                    DataView dv = dt.DefaultView;
                    dv.Sort = "StartNo ASC,EndNo ASC";
                    dt = dv.ToTable();
                    string strId = "";
                    int editCardNum = 0;
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            strId += dr["boxno"].ToString() + "|" + dr["cardno"].ToString() + "|" + dr["startno"].ToString() + "|" + dr["endno"].ToString() + "|" +
                                     dr["DUENUMBER"].ToString() + "|" + dr["actualnumber"].ToString() + "|" + dr["missingcardno"].ToString() + ";";

                            //获取编辑前的卡片数量(实际出库数量累加)
                            editCardNum += Convert.ToInt32(dr["ACTUALNUMBER"].ToString());
                        }
                    }
                    hfEditSumCard.Value = editCardNum.ToString();
                    hf_CheckId.Value = strId.TrimEnd(';');
                    DataTable dtDem = new CardMaking_CardDemandDetailData().GetList(" DETAILID='" + sData.DEMANDID + "' ", "cardnumber,CardOutTotal");
                    //获取编辑时可出库的卡片数量
                    if (dtDem != null && dtDem.Rows.Count > 0)
                    {
                        hf_DemSum.Value = dtDem.Rows[0]["cardnumber"].ToString();//卡片需求单数量
                        hf_DemCkSum.Value = dtDem.Rows[0]["CardOutTotal"].ToString();//已出库数量
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (sData.ISSUBMIT == 0 || sData.ISSUBMIT == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(int.Parse(sData.ISSUBMIT.ToString()), "白卡出库");

                    //根据供应商绑定卡类型数据
                    hf_CardType.Value = sData.CARDTYPEID;//卡类型
                    btn_DemandId_ValueChanged(sender, e);
                    ddlSUPPID.SelectedValue = sData.SUPPID;
                    ddlSUPPID_selectChange(sender, e);
                    ddlCardTypeId_selectChange(sender, e);

                }
            }
            else
            {
                hfEditSumCard.Value = "0";
                OUTSTORAGENO.Value = GetBillNumber("白卡出库");
            }
        }
        #endregion

        #region 保存按钮事件
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(10, result.Split(',')[1]); //10:白卡出库
                    InsertLog("保存并提交白卡出库信息,出库单号:" + OUTSTORAGENO.Value);
                }
                else
                    InsertLog("保存白卡出库信息,出库单号:" + OUTSTORAGENO.Value);
                ReturnListInfo();
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 得到对象
        /// <summary>
        /// 白卡出库信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            CardMaking_CardOutStorage model = new CardMaking_CardOutStorage();
            model = GetWebControls<CardMaking_CardOutStorage>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;//最后修改人
            model.LASTUPDATEDATE = DateTime.Now; //最后修改时间
            model.DEMANDID = hf_DemandId.Value; //卡片需求单ID
            model.ISSUBMIT = issubmit;//0 未提交 1 待审核 2 审核中 3 驳回 4 审核不通过 5审核通过
            if (ddlSUPPID.SelectedValue != "0")
            {
                model.SUPPID = ddlSUPPID.SelectedValue;//供应商
            }
            if (hf_CardType.Value != "")
            {
                model.CARDTYPEID = hf_CardType.Value;//卡类型
            }
            FileValue = hf_CheckId.Value; //白卡出库明细字段

            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue, rkId.Value);
            }
            else
            {
                result = DAL.Add(model, FileValue, rkId.Value);
                if (result.Split(',')[0] == "ok")
                {
                    //DataTable dt = DAL.GetInfoById(result.Split(',')[1]);
                    //string outStorageNo = dt.Rows[0]["OutStorageNo"].ToString();
                    //string lastNumber = GetMAXNO("sys_billrule", "LastNum", " and billName='白卡出库' ");
                    //if (lastNumber == "0")
                    //    ChgBillNumber("白卡出库");
                    //else
                    //{
                    //    if (outStorageNo == lastNumber)
                    ChgBillNumber("白卡出库");
                    //}
                }
            }
            return result;
        }
        #endregion

        #region 绑定供应商 、盒号
        //根据申领单来绑定供应商
        protected void btn_DemandId_ValueChanged(object sender, EventArgs e)
        {
            if (hf_DemandId.Value != "")
            {
                string id = "";
                if (IsEdit)
                    id = Request.QueryString["id"];
                DtAll = DAL.GetAllInfo(id);
                if (DtAll.Rows.Count == 0)
                {
                    //当审核不通过(IsSubmit=4)时获取白卡出库供应商和盒号等信息
                    DtAll = CardLogistics.DAL.CommonData.GetList("*", "v_cardmaking_cardoutdetail", "OutStorageId='" + id + "' and IsSubmit=4");
                    //二次利用入库或者缺卡入库
                    if (DtAll.Rows.Count == 0)
                        DtAll = DAL.GetIsEcInfo(id, hf_DemandId.Value);
                }
                BindSupp();

            }
        }
        #endregion


    }
}